<?php
/**
 * QQAS - share your knowledge to the world!
 * 
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */
 
// ------------------------------------------------------------------------

/**
 * Register Class
 *
 * @category  Home
 */
class RegisterAction extends HomeAction 
{


	//初始化
	public function _initialize()
	{
		import('ORG.Net.Http');
		parent::_initialize();
	}


    //注册页
    public function index()
    {

    	$type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 'local';
    	$captcha = require_captcha_when('register');

    	if ('off' == $this->_global['register_enable'])
    	{
    		$this->error(L('register_disabled'));
    	}
    	
    	if (isset($_REQUEST['disagree']) || ('local' == $type && !empty($this->_user['user_id'])))
		{
			redirect($this->_global['site_url']);
		}
    	
    	//24小时内单IP注册量检查
    	$map = array(
    	   'register_ip'   => get_client_ip(),
    	   'register_date' => date('Y-m-d'),
    	);
    	$count = $this->_User->where($map)->count();
        if ($count >= $this->_global['max_ip_registration'])
        {
            $this->error(L('exceed_ip_registration_limit'));
        }

		$this->assign('type', $type);

		if ($this->_global['require_reg_agreement'] && !isset($_REQUEST['agree']))
    	{
    		$agreement = F('cache_registration_agreement');
    		$this->assign('agreement', $agreement);
    		$this->display('agreement');
    	}
    	else
    	{
    		$account = cookie('account');
    		$usernameExplain = 'username_'. $this->_global['username_allowed_chars'] .'_explain';
    		$passwordExplain = 'password_'. $this->_global['pwd_complex'] .'_explain';
    		
    		L('username_explain', sprintf(L($usernameExplain), $this->_global['min_username_chars'], $this->_global['max_username_chars']));
    		L('password_explain', sprintf(L($passwordExplain), $this->_global['min_pwd_chars'], $this->_global['max_pwd_chars']));
    	    
    		$this->assign('usernameExplain', $usernameExplain);
    	    $this->assign('passwordExplain', $passwordExplain);
	    	$this->assign('account', $account);
	    	$this->assign('captcha', $captcha);
	    	$this->display();
    	}
    }


    //标准本地账号注册
    public function doLocalRegister()
    {
    	
    	$Invitation = D('Invitation');
    	
    	if ($this->isPost())
    	{
    		$captcha = require_captcha_when('register');
    		
    		$usernameValidated = is_valid_username($_POST['username']);
    		$passwordValidated = is_valid_password($_POST['password']);
    		$emailValidated    = is_valid_email($_POST['email']);
    		
    		if ('invite' == $this->_global['register_enable'])
    		{
    			if (!$Invitation->checkKey($_POST['invite_key']))
    			{
    				$this->error(L('invite_key_invalid'));
    			}
    		}
    		
    		if (true !== $usernameValidated)
    		{
    			$this->error(L($usernameValidated));
    		}
    		
    		if (true !== $emailValidated)
    		{
    			$this->error(L($emailValidated));
    		}
    		
    		if (true !== $passwordValidated)
    		{
    			$this->error(L($passwordValidated));
    		}
    		
    		if ($_POST['password'] != $_POST['repassword'])
    		{
    			$this->error(L('password_not_match'));
    		}
    		
			if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
			{
				$this->error(L('captcha_incorrect'));
			}
			
			$salt = kg_password_salt();
            $inviterID = cookie('inviter_id');
            $points = get_activity_points('register');
			$requireEmailConfirm = false;

            switch (strtolower($this->_global['require_activation']))
	    	{
	    		case 'none':
	    			$userGroup = 7;
	    			$message = L('account_created');
	    		break;
	    		case 'by_user':
	    			$userGroup = 4;
	    			$message = L('account_require_confirm');
	    			$requireEmailConfirm = true;
	    		break;
	    		case 'by_admin':
	    			$userGroup = 4;
	    			$message = L('account_require_approval');
				break;
	    	}

	    	$data = array(
    			'username'      => trim($_POST['username']),
    			'password'      => kg_password_encrypt(trim($_POST['password']), $salt),
    			'salt'          => $salt,
    			'email'         => trim($_POST['email']),
    			'user_group'    => $userGroup,
    			'point_count'   => $points,
    			'register_ip'   => get_client_ip(),
    			'register_date' => date('Y-m-d'),
    			'inviter_id'    => !empty($inviterID) ? kg_auth_code($inviterID, 'decode') : 0,
    		);
    		
    		$inviter = array();
    		if ('invite' == $this->_global['register_enable'])
    		{
    			$inviter = $Invitation->getInviterByKey($_POST['invite_key']);
    			$data['inviter_id'] = $inviter['user_id'];
    		}

	    	$userID = $this->_User->add($data);
	    	
	    	if (7 == $userGroup)
	    	{
	    	    $this->_User->autoUpgradeLevel($userID);
	    	}
    		
	    	$this->_User->cookieUser($userID);
			$this->_User->logActivity($userID, 'register', $points, 0);
			
			//更新邀请码状态
			if (!empty($inviter) && !empty($_POST['invite_key']))
			{
				$inviteData = array(
					'register_user_id' => $userID,
					'register_username' => $data['username'],
					'register_time' => time(),
					'status' => 0,
				);
				$where = array(
					'user_id' => $inviter['user_id'],
					'key' => $_POST['invite_key'],
				);
				$Invitation->where($where)->save($inviteData);
			}

			//奖励邀请人以及增加关注
            if (!empty($data['inviter_id']) && 7 == $userGroup)
            {
                $Dao = D('UserFollow');
                $Dao->addFollow($userID, $data['inviter_id']);
                $this->_User->rewardInviter($data['inviter_id']);
        		cookie('inviter_id', NULL);
            }

            //发送帐号确认邮件
            if ($requireEmailConfirm)
            {
            	$requestUrl = get_site_domain() . U('Notification/confirmAccount', array('uid' => $userID));
				Http::async_request($requestUrl);
            }

	    	//发送欢迎邮件
	    	if ($this->_global['welcome_msg'])
	    	{
				$requestUrl = get_site_domain() . U('Notification/welcomeMessage', array('uid' => $userID));
				Http::async_request($requestUrl);
	    	}

	    	$jumpUrl = format_user_url($userID, $data['username']);

	    	$this->assign('jumpUrl', $jumpUrl);
	    	$this->success($message);
    	}
    }
    
    
    //第三方账号绑定
    public function doExternalRegister()
    {
    	
    	$UserAccount = D('UserAccount');
    	$UserFollow = D('UserFollow');
    	
        $account = cookie('account');
    	if (empty($account))
    	{
    		redirect($this->_global['site_url']);
    	}

    	if ($this->isPost())
    	{
    		$usernameValidated = is_valid_username($_POST['username']);
    		$emailValidated    = is_valid_email($_POST['email']);
    		
    		if (true !== $usernameValidated)
    		{
    			$this->error(L($usernameValidated));
    		}
    		
    		if (true !== $emailValidated)
    		{
    			$this->error(L($emailValidated));
    		}

    		$points = get_activity_points('register');
    		$inviterID = cookie('inviter_id');

	    	$data = array(
    			'username'      => trim($_POST['username']),
    			'email'         => trim($_POST['email']),
    			'user_group'    => 7,
    			'point_count'   => $points,
    			'register_ip'   => get_client_ip(),
    			'register_date' => date('Y-m-d'),
    			'inviter_id'    => !empty($inviterID) ? kg_auth_code($inviterID, 'decode') : 0,
    		);
	    	$userID = $this->_User->add($data);

    	    $data = array(
    			'user_id'     => $userID,
    			'hash'        => kg_crc32($account['identifier']),
    			'provider'    => $account['provider'],
    			'identifier'  => $account['identifier'],
    			'create_time' => time(),
    		);
    		$UserAccount->add($data);

    		$this->_User->autoUpgradeLevel($userID);
	    	$this->_User->logActivity($userID, 'register', $points, 0);
    		$this->cookieUser($userID);

    		//奖励邀请人以及增加关注
            if (!empty($data['inviter']))
            {
                $UserFollow->addFollow($userID, $data['inviter_id']);
                $this->_User->rewardInviter($data['inviter_id']);
        		cookie('inviter_id', NULL);
            }

    		$this->assign('jumpUrl', $this->_global['site_url']);
	    	$this->assign('waitSecond', 60);
	    	$this->success(L('account_created'));
    	}
    }
    
}
// End  Class

/* End of file RegisterAction.class.php */
/* Location: ./App/Lib/Action/Home/RegisterAction.class.php */